﻿using Authority.Model;
using AutoMapper.DTO;
using Common.Library;
using Dapper.MsSql.Library;
using MsSql.DataBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tool.Model;
using Dapper.Library;

namespace Authority.Logic
{
    public class SysRoleServiceImpl : ISysRoleService
    {
        #region 查询信息
        /// <summary>
        /// 获取所有角色信息
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<List<SysRoleEntity>> LoadAllListInfo()
        {
            var result = new ResultJsonInfo<List<SysRoleEntity>>();

            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                var listInfo = con.QuerySet<SysRoleEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();
                if (listInfo.Count > 0)
                {
                    result.Code = ActionCodes.Success;
                    result.Data = listInfo;
                }
                else
                {
                    result.Msg = "无对应信息！";
                }
            }
            return result;
        }

        /// <summary>
        /// 根据Name获取角色列表信息
        /// </summary>
        /// <param name="parametersInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<SysRoleEntity>> LoadListInfo(string sName)
        {
            var result = new ResultJsonInfo<List<SysRoleEntity>>();

            List<SysRoleEntity> listInfo = null;
            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                if (sName.IsNotNullOrEmpty())
                {
                    listInfo = con.QuerySql<SysRoleEntity>().BySql(DataCommandManager.GetSQLCommand("LoadRolesByName", "SysRole"), new { sName = sName }).Multiple();
                }
                else
                {
                    listInfo = con.QuerySet<SysRoleEntity>().AndWhere(p => p.bIsDeleted == false).OrderByAsc("iSort").Multiple();
                }
            }
            if (listInfo.Count > 0)
            {
                result.Code = ActionCodes.Success;
                result.Data = listInfo;
            }
            else
            {
                result.Msg = "无对应信息！";
            }
            return result;
        }
        #endregion

        #region 节点编辑操作

        /// <summary>
        /// 新增根节点信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> AddRoot(RoleRootRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                var result = 0;

                var sysRole = inputInfo.MapTo<SysRoleEntity>();

                //获取所有角色信息
                var sysRoleResult = con.QuerySet<SysRoleEntity>().WithNoLock().Multiple();
                double maxSort = 0;
                if (sysRoleResult.Count > 0)
                {
                    maxSort = sysRoleResult.Select(p => p.iSort).Max();
                }
                sysRole.gCode = GuidHelper.GetGuid();
                sysRole.iSort = maxSort + 1;

                result = con.CommandSet<SysRoleEntity>()
                       .IfNotExists(p => p.sName == sysRole.sName)
                       .Insert(sysRole);

                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result;
                    resultInfo.Msg = "新增根节点信息成功！";
                }
                else
                {
                    resultInfo.Msg = "操作失败,请检查名称是否重复！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 新增子节点信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> AddChild(RoleChildRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                con.Transaction(tran =>
                {
                    var result = 0;

                    var sysRole = inputInfo.MapTo<SysRoleEntity>();

                    var sysRoleResult = tran.QuerySet<SysRoleEntity>().WithNoLock().Multiple();

                    //查询出排序在该节点之后的所有节点
                    var sysRoleInfos = sysRoleResult.FindAll(p => p.iSort >= sysRole.iSort);
                    foreach (var item in sysRoleInfos)
                    {
                        item.iSort = short.Parse((item.iSort + short.Parse("1")).ToString());
                        tran.CommandSet<SysRoleEntity>().Update(item);
                    }

                    //插入数据
                    sysRole.gCode = GuidHelper.GetGuid();
                    result = tran.CommandSet<SysRoleEntity>()
                           .IfNotExists(p => p.sName == sysRole.sName)
                           .Insert(sysRole);

                    if (result > 0)
                    {
                        resultInfo.Code = ActionCodes.Success;
                        resultInfo.Data = result;
                        resultInfo.Msg = "新增子节点信息成功！";
                    }
                    else
                    {
                        resultInfo.Msg = "操作失败,请检查菜单名称是否重复！";
                    }
                });

            }
            return resultInfo;
        }

        /// <summary>
        /// 修改信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Modify(RoleModifyRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                var result = 0;

                var sysRole = inputInfo.MapTo<SysRoleEntity>();

                var sysRoleInfo = con.QuerySet<SysRoleEntity>().AndWhere(p => p.gCode == sysRole.gCode).Single();
                if (sysRoleInfo != null)
                {
                    sysRoleInfo.sName = sysRole.sName;
                    sysRoleInfo.sContent = sysRole.sContent;
                    result = con.CommandSet<SysRoleEntity>()
                        .IfNotExists(p => p.gCode != inputInfo.gCode && p.sName == inputInfo.sName)
                        .Update(sysRoleInfo);
                }
                else
                {
                    resultInfo.Msg = "无对应角色信息！";
                }
                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result;
                    resultInfo.Msg = "修改角色信息成功！";
                }
                else
                {
                    resultInfo.Msg = "操作失败,请检查名称是否重复！";
                }
            }
            return resultInfo;
        }
        #endregion

        #region 删除信息
        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> gCodeList)
        {
            var resultInfo = new ResultJsonInfo<int>();
            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                var result = 0;
                if (gCodeList.Count >= 0)
                {

                    var listCode = con.QuerySql<string>().BySql(DataCommandManager.GetSQLCommand("LoadRolesByCodes", "SysRole"),
                           new
                           {
                               gCodeList = gCodeList

                           }).Multiple();

                    var userRoleInfo = con.QuerySet<SysUserRoleEntity>().AndWhere(p => listCode.Contains(p.gRoleCode)).Multiple();
                    if (userRoleInfo.Count == 0)
                    {
                        result = con.CommandSql<int>().BySql(DataCommandManager.GetSQLCommand("BatchRemoveRoles", "SysRole"),
                           new
                           {
                               gCodeList = listCode

                           }).ExecuteNoQuery();

                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Data = result;
                            resultInfo.Msg = "操作成功！";
                        }
                        else
                        {
                            resultInfo.Msg = "操作失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "选中角色已被已被用户使用，无法删除！";
                    }
                }
                else
                {
                    resultInfo.Msg = "id为空，操作失败！";
                }
            }
            return resultInfo;
        }
        #endregion

        #region 角色授权

        /// <summary>
        /// 根据角色code和菜单code获取可操作按钮
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<RoleMenuButtonsListResponse>> LoadMenuButtonListByRoleMenuCode(RoleMenuButtonQueryRequest inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<RoleMenuButtonsListResponse>>();
            List<RoleMenuButtonsListResponse> listInfo = null;
            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {
                listInfo = con.QuerySql<RoleMenuButtonsListResponse>().BySql(DataCommandManager.GetSQLCommand("LoadMenuButtonByRoleMenuCode", "SysRole"),
                    new
                    {
                        gRoleCode = inputInfo.roleCode,
                        gMenuCode = inputInfo.menuCode
                    }).Multiple();
            }
            if (listInfo.Count > 0)
            {
                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = listInfo;
                resultInfo.Count = listInfo.Count;
                resultInfo.Msg = "获取成功！";
            }
            else
            {
                resultInfo.Msg = "获取失败！";
            }
            return resultInfo;
        }

        /// <summary>
        ///  更改角色-菜单按钮关系表信息（给角色授按钮权限）
        /// </summary>
        /// <param name="inputInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifyRoleMenuButtonInfo(RoleMenuButtonModifyRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<int>();

            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {

                var sysRoleButtonList = new List<SysRoleButtonEntity>();
                foreach (var item in inputInfo.roleMenuButtonModifyInfo)
                {
                    sysRoleButtonList.Add(item.MapTo<SysRoleButtonEntity>());
                }

                con.Transaction(tran=> {

                    // 1、先删除sysRoleButtonList中没有，数据库库中有的。
                    string[] gCodeList = sysRoleButtonList.FindAll(p=>p.gCode!=null&& p.gCode.IsNotNull() && p.gCode.ToLower()!="null").Select(p=>p.gCode).ToArray();

                    tran.CommandSet<SysRoleButtonEntity>()
                                .AndWhere(p=> p.gCode.WhereNotIn(gCodeList) && p.gRoleCode==inputInfo.gRoleCode && p.gMenuCode==inputInfo.gMenuCode)
                                .Delete();

                    foreach (var item in sysRoleButtonList)
                    {
                        if (item.gCode.IsNullOrEmpty()|| item.gCode.ToLower() == "null")
                        {
                            item.gCode = GuidHelper.GetGuid();
                            tran.CommandSet<SysRoleButtonEntity>().Insert(item);
                        }
                        else
                        {
                            tran.CommandSet<SysRoleButtonEntity>().Update(item);
                        }
                    }
                });
                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = 1;
                resultInfo.Msg = "操作成功！";
            }
            return resultInfo;
        }


        /// <summary>
        /// 给角色授菜单权限
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> ModifyRoleMenuInfo(RoleMenuModifyRequest inputInfo) {

            var resultInfo = new ResultJsonInfo<int>();

            using (var con = DataBase.GetConnection(DatabaseName.AuthorityDB.GetEnumItemDescription()))
            {

                //获取选中的所有节点和父节点
                #region 获取选中的所有节点和父节点

                var menuCodes = inputInfo.gMenuCodeList.ToArray();

                var menuList = con.QuerySql<SysMenuEntity>().BySql(DataCommandManager.GetSQLCommand("LoadAllTreeMenusListBygCodes", "SysMenu"),
                    new { gCodes = menuCodes }).Multiple();

                menuCodes = menuList.Select(p => p.gCode).ToArray();

                #endregion


                //获取该角色原有的菜单权限
                var roleMenuListInfo = con.QuerySet<SysRoleMenuEntity>()
                                .AndWhere(p => p.gRoleCode == inputInfo.gRoleCode)
                                .Multiple();

                //1、获取需要删除的，删除掉。
                var needRemoveRoleMenuListInfo = roleMenuListInfo.FindAll(p=> !menuCodes.Contains(p.gMenuCode))
                                .Select(p => p.gMenuCode)
                                .ToArray();
                //删除掉不用的菜单
                con.CommandSet<SysRoleMenuEntity>()
                                .AndWhere(p => p.gMenuCode.WhereIn(needRemoveRoleMenuListInfo) && p.gRoleCode == inputInfo.gRoleCode)
                                .Delete();

                //2、获取需要增加的，增加上。
                var needAddRoleMenuListInfo = menuCodes.ToList()
                                .FindAll(p => !roleMenuListInfo.Select(roleMenu => roleMenu.gMenuCode).Contains(p));

                List<SysRoleMenuEntity> roleMenus = new List<SysRoleMenuEntity>();
                SysRoleMenuEntity roleMenuItem = null;
                foreach (var item in needAddRoleMenuListInfo)
                {
                    roleMenuItem = new SysRoleMenuEntity();
                    roleMenuItem.gCode = GuidHelper.GetGuid();
                    roleMenuItem.gRoleCode = inputInfo.gRoleCode;
                    roleMenuItem.gMenuCode = item;
                    roleMenus.Add(roleMenuItem);
                }
                con.CommandSet<SysRoleMenuEntity>().BatchInsert(roleMenus);

                resultInfo.Code = ActionCodes.Success;
                resultInfo.Data = 1;
                resultInfo.Msg = "操作成功！";
            }
            return resultInfo;
        }
        #endregion
    }
}
